package thread;

/*
 * @author zzr
 * @date: 2025/04/17  18:42
 * @description:
 */

class MyBlockingQueue {
    private String[] elems = null;
    private int head = 0;
    private int tail = 0;
    private int size = 0;

    Object locker = new Object();

    public MyBlockingQueue(int capacity) {
        this.elems = new String[capacity];
    }

    public void put(String elem) throws InterruptedException {
        synchronized (locker) {
            while (size >= elems.length) {
                // 阻塞
                locker.wait();
            }

            if (tail >= elems.length) {
                tail = 0;
            }

            elems[tail] = elem;
            tail++;
            size++;

            // 添加元素成功要 notify
            locker.notify();
        }
    }

    public String take() throws InterruptedException {

        String elem = null;

        synchronized (locker) {
            while (0 == size) {
                locker.wait();
            }

            if (head >= elems.length) {
                head = 0;
            }

            elem = elems[head];
            head++;
            size--;

            locker.notify();
        }
        return elem;
    }
}

public class Thread19 {
    public static void main(String[] args) {
        MyBlockingQueue myBlockingQueue = new MyBlockingQueue(1000);

        // 生产者
        Thread t1 = new Thread(() -> {
            int n = 1;
            while (true) {
                try {
                    myBlockingQueue.put(n + "");
                    System.out.println("生产元素" + n);
                    n++;
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });

        // 消费者
        Thread t2 = new Thread(() -> {
            while (true) {
                try {
                    String elem = myBlockingQueue.take();
                    System.out.println("消费元素" + elem);
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });

        t1.start();
        t2.start();
    }
}
